package com.hiwan.system.web.org;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hiwan.system.pojo.DeptInfo;
import com.hiwan.system.pojo.OrgCacheInfo;
import com.hiwan.system.pojo.OrgInfo;
import com.hiwan.system.pojo.TreeNode;
import com.hiwan.system.pojo.UserInfo;
import com.hiwan.system.service.dept.DeptService;
import com.hiwan.system.service.org.OrgService;
import com.hiwan.system.service.user.UserService;
import com.hiwan.system.util.UserCacheUtils;

@Controller
@RequestMapping("/org")
public class OrgController {
	
	@Autowired
	private OrgService orgService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private UserService userService;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping("/toQuery.do")
	public String toQuery(HttpSession session,ModelMap model) {

		String rootOrgId =String.valueOf(UserCacheUtils.getOrgId());
		model.put("rootOrgId", rootOrgId);
		return "org/orgFrame";
	}
	
	/**
	 * 查询节点下的节点信息
	 * @param id 节点id
	 * @param messageType 节点属性（自定义），分org/dept
	 * @param checkType 机构树类型 分org(只展示机构)/dept(展示机构、部门)
	 * @param isCheckOrg 1--机构部门树;0--用户机构树
	 * @param noSuper
	 * @param session
	 * @param model
	 * @return
	 * @throws NoSuchFieldException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping("/haveRootNodes")
	public String haveRootNodes(String id, String messageType,
			String checkType,String isCheckOrg, String noSuper, HttpSession session, ModelMap model)
			throws NoSuchFieldException, JsonParseException,
			JsonMappingException, IOException {
		if (StringUtils.isEmpty(id)) {
			
			id = String.valueOf(UserCacheUtils.getOrgId());
		}
		if (StringUtils.isEmpty(messageType)) {
			messageType = "org";
		}
		if (StringUtils.isEmpty(checkType)) {
			checkType = "org";
		}
		List<TreeNode> nodeList = orgService.haveChildNode(messageType, id, checkType,"isRoot", noSuper, isCheckOrg);
		JSONArray jsonArray = JSONArray.fromObject( nodeList );  
		model.put("rootOrgId", id);
		model.put("jsonArray", jsonArray.toString());
		model.put("checkType", checkType);
		if (StringUtils.equals(isCheckOrg, "0")) {
			return "user/userTree";
		}
		if (StringUtils.equals(isCheckOrg, "map")) {
			return "map/mapTree";
		}
		return "org/orgTree";
	}
	/**
	 * 
	 * @param id 节点id
	 * @param messageType 节点属性（自定义），分org/dept
	 * @param checkType 机构树类型 分org(只展示机构)/dept(展示机构、部门)
	 * @param session
	 * @param model
	 * @return
	 * @throws NoSuchFieldException
	 */
	@RequestMapping("/haveChildNodes")
	public @ResponseBody String haveChildNode(String id,String checkType,String messageType,String isCheckOrg,HttpSession session,ModelMap model) throws NoSuchFieldException{
		if(StringUtils.isEmpty(id)) {
			
			id = String.valueOf(UserCacheUtils.getOrgId());
		}
		List<TreeNode> nodeList= orgService.haveChildNode(messageType, id, checkType, isCheckOrg);
		String childNode = JSONArray.fromObject( nodeList ).toString(); 
		System.err.println("childNode==" + childNode);
		return childNode;
	}
	
	/**
	 * 根据选择的节点跳转到机构新增
	 * @param pId 所选节点的id
	 * @param model
	 * @return
	 */
	@RequestMapping("toAddOrg")
	public String toAddOrg(String pId ,ModelMap model){
		//根据父机构设置新增机构的上级机构，子节点为0，树形结构层级，统计归属机构
		OrgInfo orgInfo = orgService.haveOrgInsert(pId);
		model.put("orgInfo", orgInfo);
		model.put("openFlag", "1");
		return "org/orgDetail";
	}
	/**
	 * 根据机构id查询机构的详细信息
	 * @param orgId  机构id
	 * @param model
	 * @return
	 */
	@RequestMapping("orgDetail")
	public String toModigyOrg(@RequestParam("orgId") String orgId,ModelMap model){
		OrgInfo orgInfo = orgService.getOnlyOrgInfo(orgId);
		
		model.put("orgInfo", orgInfo);
		model.put("openFlag", "3");
		return "org/orgDetail";
	}
	/**
	 * 保存机构信息
	 * @param orgInfo 机构信息
	 * @param openFlag 操作类型( 1-新增 2-修改 )
	 * @param session
	 * @return
	 * @throws NoSuchFieldException
	 */
	@RequestMapping("saveOrgInfo")
	public @ResponseBody String saveOrg(OrgInfo orgInfo,String openFlag,HttpSession session) throws NoSuchFieldException{
		String message;
		try {
			
			message = orgService.saveOrgInfo(orgInfo, openFlag, String.valueOf(UserCacheUtils.getUser().getUserId()));
		} catch (Exception e) {
			message = e.getMessage();
			e.printStackTrace();
		}
		return message; 
	}
	/**
	 * 删除机构信息
	 * @param orgInfo 机构信息
	 * @param session
	 * @return
	 */
	@RequestMapping("deleteOrg")
	public @ResponseBody String deleteOrg(OrgInfo orgInfo,HttpSession session){
		String message = null;
		try {
//			System.out.println(orgService.hasDept());
//			System.out.println(orgInfo.getOrgId());
//			List<UserInfo> userInfoList = userService.getUserInfoList();
//			for (int i = 0; i < userInfoList.size(); i++) {
//				if (orgInfo.getOrgId().equals(userInfoList.get(i).getOrgId())) {
//					message ="{\"fail\":\"机构下有用户，需先删除用户才能删除机构!\"}";
//					return message;
//				}
//			}
//			if(orgService.hasDept()){
//				message ="{\"fail\":\"机构下有子部门，需先删除子部门才能删除机构!\"}";
//				return message;
//			}else {
				message = orgService.deleteOrgInfo(orgInfo, String.valueOf(session.getAttribute("sessionUserId")));
//			}
		} catch (Exception e) {
			message = e.getMessage();
		}
		
		return message;
	}
	/**
	 * 根据选择的节点跳转到部门新增
	 * @param pId 所选节点的id
	 * @param nodeType 所选节点的类型
	 * @param model
	 * @return
	 */
	@RequestMapping("toAddDept")
	public String toAddDept(String pId,String nodeType,ModelMap model){
		DeptInfo deptInfo = new DeptInfo();
		if("org".equals(nodeType)){//在机构下面新增部门(设置部门的级别，所属机构)
			OrgCacheInfo pOrgInfo = orgService.getOrgInfo(pId);
			deptInfo.setDeptLevel("1");//设置为一级部门
			deptInfo.setBelongOrg(pOrgInfo.getOrgId());
		}else if("dept".equals(nodeType)){//在部门下面新增部门(设置部门的级别，所属的机构为父机构所属机构，上级部门)
			DeptInfo pDept = deptService.getDeptInfo(pId);
			 deptInfo.setDeptLevel("2");//设置为二级部门
	    	 deptInfo.setBelongOrg(pDept.getBelongOrg());//根据选择的部门确定所属机构
	    	 deptInfo.setParentDept(pDept.getDeptId());
		}
		OrgCacheInfo org = orgService.getOrgInfo(deptInfo.getBelongOrg());
		if( orgService.getOrgInfo(deptInfo.getBelongOrg() + "V")!=null){
   		 if(org.getTreeLevel().equals("2")){//市分行
   			 deptInfo.setToOrgId(deptInfo.getBelongOrg() + "J"); 
   		 }else{//其他
   			 deptInfo.setToOrgId(deptInfo.getBelongOrg() + "V"); 
   		 }
   	 }else{
   		 deptInfo.setToOrgId(deptInfo.getBelongOrg()); 
   	 }
		
		model.put("deptInfo",deptInfo);
		model.put("openFlag", "1");
		return "org/deptDetail";
	}

	/**
	 * 保存新增的部门信息
	 * @param deptInfo 新增的部门信息
	 * @param session
	 * @return
	 */
	@RequestMapping("saveDept")
	public @ResponseBody String saveDept(DeptInfo deptInfo,HttpSession session){
		String message ="";
		deptInfo.setCreateUser(UserCacheUtils.getUser().getUserId());//根据session设置部门信息的创建人
		deptInfo.setCreateTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));//设置创建时间
		try{
			boolean isExist = checkDeptName(deptInfo);
			if(isExist){
				message ="{\"fail\":\"名称已经存在，请重新输入名称!\"}";
			}else{
				DeptInfo info=deptService.getDeptInfo(deptInfo.getDeptId());
				if(StringUtils.isBlank(info.getDeptId())){
					deptService.insertEntry(deptInfo);//新增入库
					message = "{\"success\":\"新增部门成功!\",\"retDeptId\":"+deptInfo.getDeptId()+"}";
				}else{
					message ="{\"fail\":\"部门编号已经存在，请重新输入!\"}";
				}
			}
		}catch(Exception e){
			message = "{\"fail\":\"新增部门失败!\",\"errorCode\":e.getErrorCode()}";
		}
		return message;
	}
	/**
	 * 根据部门id查询部门的详细信息
	 * @param deptId 部门id
	 * @param model
	 * @return
	 */
	@RequestMapping("deptDetail")
	public String deptDetail(String deptId, ModelMap model){
		DeptInfo deptInfo = deptService.getDeptInfo(deptId);
		model.put("openFlag", "3");
		model.put("deptInfo", deptInfo);
		return "org/deptDetail";
	}
	/**
	 * 修改部门信息
	 * @param deptInfo 部门信息
	 * @param session
	 * @return
	 */
	@RequestMapping("updateDept")
	public @ResponseBody String updateDept(DeptInfo deptInfo,HttpSession session,String oriDeptId){
		String message = null;
		deptInfo.setCreateUser(UserCacheUtils.getUser().getUserId());
		deptInfo.setUpdateUser(UserCacheUtils.getUser().getUserId());//根据session设置修改部门信息的修改人id
		deptInfo.setUpdateTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));//设置修改时间
		try{
			boolean isExist = checkDeptName(deptInfo);
			if(isExist){
				message ="{\"fail\":\"名称已经存在，请输入名称!\"}";				
			}else{
				if(!StringUtils.equals(oriDeptId, deptInfo.getDeptId())){
					
					DeptInfo info=deptService.getDeptInfo(deptInfo.getDeptId());
					if(StringUtils.isBlank(info.getDeptId())){
						deptInfo.setDeptForId(deptInfo.getDeptId());
						deptInfo.setDeptId(oriDeptId);
						deptService.modifyEntry(deptInfo);
						message ="{\"success\":\"修改部门成功!\",\"retDeptId\":"+deptInfo.getDeptForId()+"}";
					}else{
						message ="{\"fail\":\"部门编号已经存在，请重新输入!\"}";
					}
					
				}else{
					
					deptService.modifyEntry(deptInfo);
					message ="{\"success\":\"修改部门成功!\",\"retDeptId\":"+deptInfo.getDeptId()+"}";
				}
				
			}
		}catch(Exception e){
			message = "{\"fail\":\"修改部门失败!\",\"errorCode\":e.getErrorCode()}";
		}
		return message;
	}
	public boolean checkDeptName(DeptInfo deptInfo){
		return orgService.getDeptByName(deptInfo);
		
	}
	/**
	 * 删除部门信息
	 * @param deptInfo 部门信息
	 * @param model
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping("deleteDept")
	public @ResponseBody String deleteDept(DeptInfo deptInfo,ModelMap model) throws SQLException{
		String message = "";
		try{
			Boolean flage = checkDeptChild(deptInfo);
			
			if(!flage){
			deptService.deleteEntry(deptInfo);
			message = "{\"success\":\"删除部门成功!\"}";
			}else{
			
				message="{\"fail\":\"该部门下有子部门，不能删除!\"}";
			}
			List<UserInfo> userInfoList = userService.getUserInfoList();
			for (int i = 0; i < userInfoList.size(); i++) {
				if (deptInfo.getDeptId().equals(userInfoList.get(i).getDeptId())) {
					message ="{\"fail\":\"部门下有用户，需先删除用户才能删除部门!\"}";
					return message;
				}
			}
		}catch(Exception e){
			message = "{\"fail\":\"删除部门失败!\",\"errorCode\":e.getErrorCode()}";
		}
		return message;
	}
	
	
	public boolean checkDeptChild(DeptInfo deptInfo){
		List<DeptInfo> deptInfoList = deptService.getDeptList(null, deptInfo.getDeptId(), "deptA");
		System.out.println("deptInfoList:"+deptInfoList);
		if(deptInfoList.size()>0){
			return true;
		}
		return false;
	}
	
	/**
	 * 机构选择
	 * @param rootOrgId 节点id
	 * @param checkType org-机构;dept-部门;
	 * @param params jquery-hiwan.js中传递的参数
	 * @throws IOException 
	 * @throws JsonProcessingException 
	 * @throws NoSuchFieldException 
	 */
	@RequestMapping("/orgSelectTree")
	public String orgSelectTree(String rootOrgId, ModelMap model,
			HttpSession session,@RequestParam("params") String params) throws JsonProcessingException, IOException, NoSuchFieldException {
		
		ObjectMapper mapper = new ObjectMapper();
		JsonNode jsonParams = mapper.readTree(params);
		
		if (StringUtils.isBlank(rootOrgId)) {
			String temp = jsonParams.findValue("id").getTextValue();
			if(StringUtils.isNotBlank(temp)){
				rootOrgId = temp;
			}else{
				rootOrgId = String.valueOf(UserCacheUtils.getOrgId());
			}
		}
		
		
		String checkType = jsonParams.findValue("checkType").getTextValue();
		String clickType = jsonParams.findValue("clickType").getTextValue();
		
		List<TreeNode> nodeList = orgService.haveChildNode("org", rootOrgId, checkType,"isRoot", "", "");
		JSONArray arrayList = JSONArray.fromObject(nodeList);
		
		model.put("rootOrgId", rootOrgId);
		model.put("childrenNodes", arrayList.toString());
		model.put("checkType", checkType);
		model.put("clickType", clickType);
		
		return "org/orgSelect";
	}
	/**
	 *部门选择
	 * @param 所属机构 节点id
	 * @param params jquery-hiwan.js中传递的参数
	 * @throws IOException 
	 * @throws JsonProcessingException 
	 * @throws NoSuchFieldException 
	 */
	@RequestMapping("/deptSelectTree")
	public String deptSelectTree( ModelMap model,
			HttpSession session,@RequestParam("params") String params) throws JsonProcessingException, IOException, NoSuchFieldException {
		
		ObjectMapper mapper = new ObjectMapper();
		JsonNode jsonParams = mapper.readTree(params);
		//String checkType = jsonParams.findValue("checkType").getTextValue();
		String clickType = jsonParams.findValue("clickType").getTextValue();
		String rootOrgId = jsonParams.findValue("orgId").getTextValue();
		if(StringUtils.isEmpty(rootOrgId)){
			rootOrgId = String.valueOf(UserCacheUtils.getOrgId());
		}
		/*if (StringUtils.isEmpty(rootOrgId)) {
			rootOrgId = String.valueOf(UserCacheUtils.getOrgId());
		}*/
		
		List<TreeNode> nodeList = orgService.getDeptList(rootOrgId);
		JSONArray arrayList = JSONArray.fromObject(nodeList);
		
		model.put("rootOrgId", rootOrgId);
		model.put("deptNodes", arrayList.toString());
		//model.put("checkType", checkType);
		model.put("clickType", clickType);
		
		return "org/deptSelect";
	}
	
	@RequestMapping("mobile/getOrgInfo")
	@ResponseBody
	public Map<String, Object> getOrgInfo(ModelMap model, String orgId){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			map.put("result", "success");
			map.put("msg", "查询成功！");
			OrgCacheInfo orgCacheInfo = orgService.getOrgInfo(orgId);
			map.put("data", orgCacheInfo);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "fail");
			map.put("msg", "查询异常！");
		}
		return map;
	}
	
	@RequestMapping("mobile/getOrgName")
	@ResponseBody
	public Map<String, Object> getOrgName(ModelMap model, String orgId){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			map.put("result", "success");
			map.put("msg", "查询成功！");
			String orgName = orgService.getOrgName(orgId);
			map.put("orgName", orgName);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "fail");
			map.put("msg", "查询异常！");
		}
		return map;
	}
	/**
	 * 区行
	 * @param channel
	 * @return
	 */
//	@RequestMapping("mobile/getOrgRegion")
//	@ResponseBody
//	public Map<String,Object> getOrgRegion(OrgInfo orgInfo){
//		Map<String,Object> map=new HashMap<String,Object>();
//		List<OrgInfo> object=orgService.getOrgRegion(orgInfo);
//		ReturnInfo returnInfo=new ReturnInfo();
//		returnInfo.setRetcode(ReturnCodeEnum.success.getCode());
//		returnInfo.setRetmsg(ReturnCodeEnum.success.getDesc());
//		returnInfo.setResult(object);
//		map.put("data", returnInfo);
//		return map;
//	}
	/**
	 * 支行
	 * @param channel
	 * @return
	 */
//	@RequestMapping("mobile/getOrgBranch")
//	@ResponseBody
//	public Map<String,Object> getOrgBranch(OrgInfo orgInfo){
//		Map<String,Object> map=new HashMap<String,Object>();
//		List<OrgInfo> object=orgService.getOrgBranch(orgInfo);
//		ReturnInfo returnInfo=new ReturnInfo();
//		returnInfo.setRetcode(ReturnCodeEnum.success.getCode());
//		returnInfo.setRetmsg(ReturnCodeEnum.success.getDesc());
//		returnInfo.setResult(object);
//		map.put("data", returnInfo);
//		return map;
//	}
	
}
